import 'dart:async';

import 'package:common_utils/common_utils.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_widget_from_html/flutter_widget_from_html.dart';
import 'package:flutterlib/common/constants/constants.dart';
import 'package:flutterlib/common/net/retrofit/activity_api.dart';
import 'package:flutterlib/common/net/retrofit/post_api.dart';
import 'package:flutterlib/common/style/font_awesome4_icons.dart';
import 'package:flutterlib/common/style/meterial_design_icons.dart';
import 'package:flutterlib/common/utils/color_utils.dart';
import 'package:flutterlib/common/utils/navigator_utils.dart';
import 'package:flutterlib/common/utils/toast.dart';
import 'package:flutterlib/common/utils/utils.dart';
import 'package:flutterlib/model/activity/activity_detail_bean.dart';
import 'package:flutterlib/model/activity/activity_join_request.dart';
import 'package:flutterlib/model/post/comment_bean.dart';
import 'package:flutterlib/model/post/comment_bean_tree.dart';
import 'package:flutterlib/model/post/comment_request.dart';
import 'package:flutterlib/pages/activity/viewmodel/activity_store.dart';
import 'package:flutterlib/widgets/bussiness/user_info_widget.dart';
import 'package:flutterlib/widgets/dialog/flutter_custom_dialog.dart';
import 'package:flutterlib/widgets/dialog/input_dialog.dart';
import 'package:flutterlib/widgets/dialog/text_input_dialog.dart';
import 'package:flutterlib/widgets/image/load_image.dart';
import 'package:like_button/like_button.dart';
import 'package:mobx/mobx.dart';
import 'package:thrio/thrio.dart';
import 'package:flutterlib/common/datacenter/config_data_center.dart';

const String STATIC_STRING_TYPE = "类型";
const String STATIC_STRING_TIME = "时间";
const String STATIC_STRING_ADDRESS = "地址";
const String STATIC_STRING_RELATE_INTEREST = "关联兴趣";
const String STATIC_STRING_RELATE_GROUP = "关联圈子";
const String STATIC_STRING_COMMENTS = "评价";
const String STATIC_STRING_CHECK_COMMENTS = "查看全部>";
const String STATIC_STRING_CONNECT_WITH_ME = "和我联系";
const String STATIC_STRING_TAKE_PART_IN = "申请参加";
const String STATIC_STRING_ALREADY_APPLY = "已申请";
const String STATIC_STRING_JOINED = "已参加";

class Page extends StatefulWidget {
  Page({this.id});

  final int id;

  @override
  PageState createState() => PageState();
}

class PageState extends State<Page> with SingleTickerProviderStateMixin {
  ActivityStore _store = ActivityStore();

  ActivityDetailBean activity;
  final LoadingDialogController loadingDialogController =
      LoadingDialogController();
  final StreamController<bool> titleAnimateStreamController =
      StreamController<bool>.broadcast();

  double get tabBarHeight => 56.h;

  double get expandedHeight => Screens.width / 2 + tabBarHeight;

  Stream<bool> get titleAnimateStream => titleAnimateStreamController.stream;
  final ScrollController scrollController = ScrollController();

  String get applyBtnStr {
    if (activity.isApply) {
      return STATIC_STRING_ALREADY_APPLY;
    }
    if (activity.isJoined) {
      return STATIC_STRING_JOINED;
    }
    return STATIC_STRING_TAKE_PART_IN;
  }

  @override
  void initState() {
    super.initState();

    _store.fetchActivity(widget.id);
    ActivityApi.builder().viewActivity(widget.id);

    _store.fetchActivityComment(widget.id, 0, "createTime,desc");
  }

  void listener() {
    double triggerHeight = expandedHeight - kToolbarHeight;
    triggerHeight -= tabBarHeight;
    titleAnimateStreamController.add(scrollController.offset >= triggerHeight);
  }

  @override
  void dispose() {
    scrollController?.dispose();
    super.dispose();
  }

  @override
  void didChangeDependencies() {
    scrollController
      ..removeListener(listener)
      ..addListener(listener);
  }

  Widget appbar() {
    return StreamBuilder<bool>(
      initialData: false,
      stream: titleAnimateStream,
      builder: (BuildContext _, AsyncSnapshot<bool> data) {
        final bool shouldTitleDisplay = data.data;
        return SliverAppBar(
          brightness: shouldTitleDisplay
              ? context.themeData.brightness
              : Brightness.dark,
          expandedHeight: expandedHeight,
          elevation: 0.0,
          pinned: true,
          leading: MyBackButton(
            color: shouldTitleDisplay ? null : Colors.white,
          ),
          centerTitle: true,
          actions: [
            _buildMoreAction(context),
            SizedBox(
              width: 15,
            )
          ],
          title: AnimatedSwitcher(
            duration: kThemeChangeDuration,
            child: shouldTitleDisplay
                ? appBarTitleWidget
                : const SizedBox.shrink(),
          ),
          flexibleSpace: FlexibleSpaceBar(
            collapseMode: CollapseMode.pin,
            background: appBarBackgroundWidget,
          ),
        );
      },
    );
  }
  Widget get appBarTitleWidget {
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: <Widget>[
        Expanded(
          child: Text(
            activity?.aim ?? '',
            style: QuhuiConstant.smallTextWhite,
          ),
        ),

      ],
    );
  }


  Widget get appBarBackgroundWidget {
    return getPhotos();
  }

  @override
  Widget build(BuildContext context) {
    return Observer(builder: (_) {
      if (_store.activityFuture.status != FutureStatus.fulfilled) {
        return Container();
        // return new Scaffold(
        //   body: Container(
        //     color: QuhuiColors.white,
        //     child: Center(
        //       child: Loading(
        //           indicator: BallBeatIndicator(),
        //           size: 20.0,
        //           color: QuhuiColors.mainThemeColor),
        //     ),
        //   ),
        // );
      }

      activity = _store.activityFuture.result;
      print(activity);
      return Scaffold(
        body: NestedScrollView(
            controller: scrollController,
            headerSliverBuilder: (c, s) => [
                  appbar(),
                ],
            body: getBody()),
        bottomNavigationBar: getDecision(),
      );
    });
  }

  Widget getBody() {
    return SingleChildScrollView(
        child: Container(
            child: Column(
      children: [
        Container(
          child: Column(
            children: [
              getIntro(),
              Container(
                height: 10,
                color: QuhuiColors.e9Color,
              ),
              getComments(),
              Container(
                height: 10,
                color: QuhuiColors.e9Color,
              ),
            ],
          ),
        ),
        getDescription(),
        const SizedBox(
          height: 70,
        )
      ],
    )));
  }

  Widget getPhotos() {
    return Container(
      height: 264,
      child: LoadImage(
        activity?.logo,
        fit: BoxFit.cover,
      ),
      // decoration: BoxDecoration(
      //     image: DecorationImage(
      //         image: AssetImage("assets/images/webInterFace.png"),
      //         fit: BoxFit.fill))
    );
  }

  Widget getIntro() {
    return Padding(
        padding: EdgeInsets.only(left: 16, right: 16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Padding(
                padding: EdgeInsets.only(top: 16, bottom: 16),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Expanded(
                        child: Text(
                      activity?.aim,
                      style: TextStyle(
                          fontSize: 16, fontWeight: FontWeight.bold),
                    )),
                    SizedBox(
                      width: 8,
                    ),
                    Text(
                      '浏览${activity.looknum}次',
                      style:
                          TextStyle(fontSize: 12, color: HexColor("#666666")),
                    )
                  ],
                )),
            Text(
              "${activity.cost}",
              style: TextStyle(color: HexColor("#178F64"), fontSize: 15),
            ),
            Padding(
                padding: EdgeInsets.only(top: 32, bottom: 32),
                child: Column(
                  children: [
                    Row(
                      children: [
                        const Text(
                          STATIC_STRING_TYPE,
                          style: TextStyle(color: Colors.grey, fontSize: 15),
                        ),
                        SizedBox(
                          width: 20,
                        ),
                        Text(
                          activity.type == 1
                              ? '招募活动'
                              : ActivityForm
                                  .values[(activity.form ?? 0) %
                                      ActivityForm.values.length]
                                  .title,
                          style: TextStyle(fontSize: 15),
                        )
                      ],
                    ),
                    SizedBox(
                      height: 16,
                    ),
                    Row(
                      children: [
                        const Text(STATIC_STRING_TIME,
                            style:
                                TextStyle(color: Colors.grey, fontSize: 15)),
                        SizedBox(
                          width: 20,
                        ),
                        Text(
                          '${DateUtil.formatDateMs(activity.startTime * 1000, format: DateFormats.y_mo_d)} -'
                          '${DateUtil.formatDateMs(activity.endTime * 1000, format: DateFormats.y_mo_d)}',
                          style: TextStyle(fontSize: 15),
                        )
                      ],
                    ),
                    SizedBox(
                      height: 16,
                    ),
                    activity.type == 1
                        ? Row(children: [
                            const Text(STATIC_STRING_RELATE_INTEREST,
                                style: TextStyle(
                                    color: Colors.grey, fontSize: 15)),
                            SizedBox(
                              width: 20,
                            ),
                            Expanded(
                              child: Text(
                                (getInterestFromId(activity.groupId)?.name ??
                                    ''),
                                style: TextStyle(fontSize: 15),
                              ),
                            ),
                          ])
                        : Row(children: [
                            const Text(STATIC_STRING_RELATE_GROUP,
                                style: TextStyle(
                                    color: Colors.grey, fontSize: 15)),
                            SizedBox(
                              width: 20,
                            ),
                            Expanded(
                              child: Container(),
                            ),
                            Icon(
                              AIcon.right_open,
                              size: 12,
                            ),
                          ]),
                    activity.isOnline > 0
                        ? Row(children: [
                            const Text(STATIC_STRING_ADDRESS,
                                style: TextStyle(
                                    color: Colors.grey, fontSize: 15)),
                            SizedBox(
                              width: 20,
                            ),
                            Expanded(
                              child: Text(
                                '线上',
                                style: TextStyle(fontSize: 15),
                              ),
                            ),
                          ])
                        : Row(
                            children: [
                              const Text(STATIC_STRING_ADDRESS,
                                  style: TextStyle(
                                      color: Colors.grey, fontSize: 15)),
                              SizedBox(
                                width: 20,
                              ),
                              Expanded(
                                child: Text(
                                  '${activity.address}',
                                  style: TextStyle(fontSize: 15),
                                ),
                              ),
                              SizedBox(
                                width: 10,
                              ),
                              SizedBox(
                                width: 20,
                                height: 20,
                                child: GestureDetector(
                                    onTap: () {
                                      var pointFromStr =
                                          DistanceUtil.getPointFromStr(
                                              activity.location);
                                      if (pointFromStr == null) {
                                        ToastUtils.toast("无法显示地址");
                                      } else {
                                        NavigatorUtils.gotoShowAddress(
                                            context,
                                            activity.address,
                                            pointFromStr);
                                      }
                                    },
                                    child: Image.asset(
                                        "assets/images/location.png")),
                              )
                            ],
                          ),
                  ],
                )),
            getParticipates(),
          ],
        ));
  }

  void reload(fn){
    setState(fn);
  }

  Widget getParticipates() {
    var list = activity.joinMembers
        .filter((element) => element.userId != activity.userId)
        .toList();
    int n = 3;
    List<Widget> images = List.generate(
        (list?.length ?? 0) > n ? n : (list?.length ?? 0), (index) {
      return SizedBox(
        width: 20,
        height: 20,
        child: LoadImage(
          list[index]?.userLogo ?? '',
          holderImg: 'mine_default',
          fit: BoxFit.contain,
        ),
      );
    });

    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: () {
        NavigatorUtils.gotoJoinMemberPage(context, activity.joinMembers);
      },
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Container(
            child: Row(
              children: images,
            ),
          ),
          FlatButton(
              child: Text(
                '已有${list.length}人报名',
                style: TextStyle(fontSize: 12),
              ),
              onPressed: () {}),
        ],
      ),
    );
  }

  Widget getComments() {
    return Observer(builder: (_) {
      var activityCommentFuture = _store.activityCommentFuture;
      if (activityCommentFuture.status == FutureStatus.fulfilled) {
        CommentBeanTree data = activityCommentFuture.result;
        List<CommentBean> content = data.content;
        int length = content?.length ?? 0;

        return Padding(
            padding: EdgeInsets.only(left: 16, right: 16),
            child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Padding(
                      padding: EdgeInsets.only(top: 16, bottom: 16),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Expanded(
                              child: const Text(
                            STATIC_STRING_COMMENTS,
                            style: TextStyle(
                                fontSize: 16, fontWeight: FontWeight.bold),
                          )),
                          FlatButton(
                            child: Text(STATIC_STRING_CHECK_COMMENTS),
                            onPressed: () {
                              NavigatorUtils.gotoActivityComment(widget.id);
                            },
                          )
                        ],
                      )),
                  length == 0
                      ? Container(
                          child: Padding(
                            padding: const EdgeInsets.symmetric(vertical: 8),
                            child: Text('暂无数据'),
                          ),
                        )
                      : Container(),
                  length > 0 ? CommentItem(content[0]) : Container(),
                  length > 1 ? CommentItem(content[1]) : Container(),
                ]));
      } else {
        return Container();
      }
    });
  }

  Widget getDescription() {
    return AutoFitWebView(
      content: activity.description,
    );
  }

  Widget getDecision() {
    return Container(
        height: 49,
        decoration: BoxDecoration(
            color: Colors.white,
            border:
                Border(top: BorderSide(width: 1, color: Colors.lightGreen))),
        padding: EdgeInsets.fromLTRB(10, 5, 10, 5),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 20),
                  child: LikeButton(
                      isLiked: activity.isLiked ?? false,
                      onTap: (islike) {
                        return onZhanPressed(islike);
                      },
                      size: 50,
                      circleColor: CircleColor(
                          start: Color(0xff00ddff), end: Color(0xff0099cc)),
                      bubblesColor: BubblesColor(
                        dotPrimaryColor: Color(0xff33b5e5),
                        dotSecondaryColor: Color(0xff0099cc),
                      ),
                      likeBuilder: (bool isLiked) {
                        return Icon(
                          MIcon.thumb_up,
                          color: isLiked ? Colors.red : Colors.grey,
                        );
                      },
                      likeCount: activity.likenum,
                      countBuilder: (int count, bool isLiked, String text) {
                        Widget result;
                        if (count == 0) {
                          result = Text(
                            "0",
                            style: QuhuiConstant.minSubText,
                          );
                        } else
                          result = Text(
                            text,
                            style: QuhuiConstant.minSubText,
                          );
                        return result;
                      }),
                ),
            InkWell(
              onTap: () {
                if (!isLogin) {
                  NavigatorUtils.goLogin(context);
                  return;
                }
                InputDialog.show(context).then((value) {
                  if (value == null || value.isEmpty) {
                    return;
                  }
                  CommentRequest request = new CommentRequest(
                    content: value,
                    postId: widget.id,
                    userId: currentUserId,
                    author: currentUser.nickName
                  );
                  var activityComments = PostApi.builder().comments(request);
                  activityComments.then((value) {
                    trueDebugPrint("flutterting write comment then call");
                    ToastUtils.success("评论成功");
                  }).catchError((onError) {
                    ToastUtils.success("评论失败");
                  });
                });
              },
              child: Padding(
                padding: const EdgeInsets.symmetric(horizontal: 20),
                child: Icon(
                  MIcon.textsms,
                ),
              ),
            ),
            RaisedButton(
                textColor: Colors.white,
                color: Colors.black,
                colorBrightness: Brightness.dark,
                shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.only(
                        topLeft: Radius.circular(16),
                        bottomLeft: Radius.circular(16))),
                child: const Text(STATIC_STRING_CONNECT_WITH_ME),
                onPressed: () {
                  if(activity.userId == currentUserId){
                    ToastUtils.toast('不能和自己对话');
                    return;
                  }
                  NavigatorUtils.gotoPersonTalk(context, activity.userId.toString());
                }),
            RaisedButton(
              textColor: Colors.white,
              color: Colors.green,
              shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.only(
                      topRight: Radius.circular(16),
                      bottomRight: Radius.circular(16))),
              child: Text(applyBtnStr),
              onPressed: () {
                joinActivity();
              },
            )
          ],
        ));
  }

  Future<bool> onZhanPressed(isLike) async {
    if (!isLogin) {
      NavigatorUtils.goLogin(context);
      return false;
    }
    if (!activity.isLiked) {
      ActivityApi.builder().like(activity.id).then((value) => reload(
          (){activity.isLiked = true;}
      ));

    } else {
      ActivityApi.builder().unLike(activity.id).then((value) => reload(
          (){activity.isLiked = false;}
      ));
    }
    return !isLike;
  }

  void joinActivity() async {
    if (activity.isJoined || activity.isApply) {
      ToastUtils.toast("不要重复申请");
      return;
    }
    if (activity.userId == currentUser.uid) {
      ToastUtils.toast("创建者不能加入");
      return;
    }

    var reason = await TextInputDialog.show(context);

    if (reason == null || reason.isEmpty) {
      return;
    }

    ActivityJoinRequest request = ActivityJoinRequest(
      activityId: widget.id,
      userId: currentUser.uid,
      reqMsg: reason,
    );
    LoadingDialog.show(
      context,
      controller: loadingDialogController,
      text: '申请中...',
    );

    try {
      var result = await ActivityApi.builder().joinActivity(request);
      if (result) {
        loadingDialogController
            .changeState('success', '申请成功', duration: 3.seconds, customPop: () {
          Navigator.pop(context);
        });
        activity.isApply = true;
      }
    } catch (e, stack) {
      trueDebugPrint("flutterting create activity error" + stack.toString());
      var message = (e?.response?.data ?? const {"message": "申请失败"})["message"]
          ?.toString();
      loadingDialogController.changeState(
        'failed',
        message,
        duration: 3.seconds,
      );
    } finally {
      if (mounted) {
        setState(() {});
      }
    }
  }

  _buildMoreAction(BuildContext context) {
    return Observer(builder: (_) {
      var future = _store.activityFuture;
      switch (future.status) {
        case FutureStatus.fulfilled:
          var activity = _store.activityFuture.result;
          bool isAuthor = currentUser != null && currentUserId == activity.userId;
          bool isDraft = activity.status == 0;
          //如果是作者并且还未审核通过,可以删除
          return (isAuthor && isDraft)
              ? InkWell(
                  onTap: () {
                    var yyDialog = YYDialog().build()
                      ..width = 120
                      ..borderRadius = 8.0
                      ..gravity = Gravity.rightTop
                      ..barrierColor = Colors.transparent
                      ..backgroundColor = QuhuiColors.miWhite
                      ..margin = EdgeInsets.only(top: 80, right: 20);
                    if (currentUser != null && currentUserId == activity.userId) {
                      yyDialog
                        // ..textClick(
                        //     padding:
                        //         EdgeInsets.fromLTRB(10.0, 16.0, 10.0, 16.0),
                        //     text: "修改",
                        //     fontSize: 16.0,
                        //     color: Colors.grey[700],
                        //     onClick: () {
                        //       NavigatorUtils.goPostCreate(
                        //           context, post.interestId, postId: post.id);
                        //     })
                        ..textClick(
                            padding:
                                EdgeInsets.fromLTRB(10.0, 16.0, 10.0, 16.0),
                            text: "删除",
                            fontSize: 16.0,
                            color: Colors.grey[700],
                            onClick: () {
                              ActivityApi.builder()
                                  .updateStatus(activity.id, 3)
                                  .then((value) {
                                    NavigatorUtils.ThrioNavigatorPop();
                              });
                            });
                    }
                    yyDialog.show();
                  },
                  child: Icon(
                    MIcon.more_vert,
                    color: QuhuiColors.primaryDarkValue,
                  ),
                )
              : Container();
          break;
        default:
          return Container();
          break;
      }
    });
  }
}

class AutoFitWebView extends StatefulWidget {
  final String url;
  final String content;

  const AutoFitWebView({Key key, this.url, this.content}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _AutoFitWebViewState();
  }
}

class _AutoFitWebViewState extends State<AutoFitWebView> {
  double height = 300;

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(10.0),
      child: SizedBox(
        height: height,
        child: (widget.content?.isNotEmpty ?? false)
            ? HtmlWidget(
                // the first parameter (`html`) is required
                widget.content,

                // set the default styling for text
                textStyle: TextStyle(fontSize: 14),

                // By default, `webView` is turned off because additional config
                // must be done for `PlatformView` to work on iOS.
                // https://pub.flutter-io.cn/packages/webview_flutter#ios
                // Make sure you have it configured before using.
                webView: true,
              )
            : WebView(
                widget.url,
                js: true,
              ),
      ),
    );
  }
}

class CommentItem extends StatelessWidget {
  final CommentBean commentBean;

  const CommentItem(this.commentBean, {Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ListTile(
      leading: UserInfoWidget(
        onPressed: () {
          NavigatorUtils.goUserHome(context, commentBean.userId);
        },
        width: 33,
        height: 33,
        image: commentBean.authorLogo,
      ),
      title: Text(
        commentBean.author,
        style: QuhuiConstant.minSubGray6Text,
      ),
      subtitle: Text(
        commentBean.content,
        style: QuhuiConstant.smallText,
      ),
    );
  }
}
